<template>
  <div class="ebook" ref="ebook">
    <ebook-reader></ebook-reader>
    <ebook-title></ebook-title>
    <ebook-menu></ebook-menu>
    <ebook-bookmask></ebook-bookmask>
  </div>
</template>

<script>
import EbookReader from '@/components/ebook/EbookReader.vue'
import EbookTitle from '@/components/ebook/EbookTitle.vue'
import EbookMenu from '@/components/ebook/EbookMenu.vue'
import EbookBookmask from '@/components/ebook/EbookBookmask.vue'
import { getReadTime, saveReadTime } from '@/utils/localStorage.js'
import { ebookMixin } from '@/utils/mixin.js'
export default {
  mixins: [ebookMixin],
  components: {
    EbookTitle,
    EbookMenu,
    EbookReader,
    EbookBookmask
  },
  watch: {
    offsetY(v) {
      if (!this.menuVisible && this.bookAvailable) {
        if (v > 0) {
          this.move(v)
        } else if (v === 0) {
          this.restore(v)
        }
      }
    }
  },
  methods: {
    // 阅读时间功能
    startLoopReadTime() {
      let readTiem = getReadTime(this.fileName)
      // console.log(readTiem)
      if (!readTiem) {
        readTiem = 0
      }
      this.task = setInterval(() => {
        readTiem++
        if (readTiem % 30 === 0) {
          saveReadTime(this.fileName, readTiem)
          console.log('存储时间', readTiem)
        }
      }, 1000)
    },
    // 拖动屏幕移动
    move(v) {
      this.$refs.ebook.style.top = v + 'px'
    },
    // 实现松手还原屏幕
    restore() {
      this.$refs.ebook.style.top = 0
      this.$refs.ebook.style.transition = 'all .2s linear'
      // 这里下拉第二次就出现不流畅的  是因为第二次下拉改变了 top 值 会触发transition动画
      // 所以要清除transition动画
      setTimeout(() => {
        this.$refs.ebook.style.transition = ''
      }, 200)
    }
  },
  mounted() {
    this.startLoopReadTime()
  },
  // 当前组件销毁时候
  beforeDestroy() {
    if (this.task) {
      // 将定时任务销毁
      clearInterval(this.task)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../assets/style/global';
.ebook {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #D2D2D1 !important;
}
</style>
